package com.santiao.fuel

import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.KeyEvent
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.santiao.publics.ad.ads.AsService
import com.santiao.publics.config.Const
import com.santiao.publics.config.Logger
import com.santiao.publics.ui.RTExitDialogPopup
import com.santiao.publics.ui.SettingFragment
import com.santiao.publics.util.LogUtil
import com.santiao.publics.util.SharedPreferencesUtil
import com.santiao.fuel.bean.BottomBarItemBean
import com.santiao.fuel.databinding.ActivityMainBinding
import com.santiao.fuel.ui.fragment.CalculatorFragment
import com.santiao.fuel.ui.fragment.MainFragment
import com.santiao.fuel.ui.fragment.WaterFragment
import com.santiao.fuel.utils.UserInfoModel
import com.santiao.publics.listener.OnScanConfigListener
import org.greenrobot.eventbus.EventBus

class MainActivity : AppCompatActivity(), OnScanConfigListener {

    val TAG = "MainActivity"

     var binding  :ActivityMainBinding? = null;
    private lateinit var topLinearLayout: LinearLayout
    private lateinit var userCenterImageView: ImageView
    private lateinit var viewPager:ViewPager



    private lateinit var my_tv_dj_number: TextView
    lateinit var contexts:Context
    lateinit var activitys: Activity


    private var fragments:MutableList<Fragment?> = arrayListOf()

    lateinit var mainFragment : MainFragment;
    lateinit var  waterFragment : WaterFragment;
    lateinit var  calculatorFragment : CalculatorFragment;
    lateinit var settingFragment : SettingFragment;



    val stackFragment = arrayOf(MainFragment() , CalculatorFragment() ,SettingFragment())
    var bottomBarItemBeans  = mutableListOf(

        BottomBarItemBean(R.drawable.tab_home_page_ic_unselect,R.drawable.tab_home_page_ic_select) ,
        BottomBarItemBean(R.drawable.tab_two_ic_unselect,R.drawable.tab_two_ic_select),
        BottomBarItemBean(R.drawable.tab_mine_ic_unselect,R.drawable.tab_mine_ic_select),
    )

    init {


    }

    companion object {

        fun forward(context: Context) {
            context.startActivity(Intent(context, MainActivity::class.java))
//            context.startActivity(Intent(context, MediationFeedRecyclerViewActivity::class.java))
        }
        @JvmStatic
        fun gotoActivity(context: Context) {
            Logger.i(Const.TAG, "MainActivity--------gotoActivity")
            FuelApplication.ifMainActivity = true
            SplashActivity.ifSplashActivity = false
//                var tag = SharedPreferencesUtil.getString("oneStatus");
            val intent = Intent(context, MainActivity::class.java)
            context.startActivity(intent)
        }
    }


    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding  = ActivityMainBinding.inflate(layoutInflater);
        setContentView(binding?.root)
        contexts=this
        activitys=this
        ImmersionBar.with(this)
            .transparentStatusBar()
            .statusBarDarkFont(true)
            .transparentNavigationBar()
            .init()


        initView();
        initEvent();

//        userCenterImageView.setOnClickListener {
//            startActivity(Intent(this,RYUserCenterActivity::class.java))
//        }

        if (UserInfoModel.getBanStatus() == "1") {
            showAlertDialog()
            return
        }


        if(AppConst.is_show_ad && UserInfoModel.getIsCurrChannel()!="0") {
        }else{
            AppConst.is_install = false
        }






    }

    private fun initView() {

        clearStyle()
        val query = findViewById<LinearLayout>(R.id.query)
        var image =query.get(0) as ImageView
        var text =query.get(1) as TextView
        image.setBackgroundResource(R.drawable.tab_home_page_ic_select)
        text.setTextColor(Color.parseColor("#6fd292"))
        changeFragments(stackFragment.elementAt(0))

        adLoad(-1,this,this)

    }

    private fun initEvent() {

        val query = findViewById<LinearLayout>(R.id.query)
        val unitChange = findViewById<LinearLayout>(R.id.unitChange)
        val mine = findViewById<LinearLayout>(R.id.mine)

        query.setOnClickListener {
            changeFragments(stackFragment.elementAt(0))
            clearStyle()
            var image =query.get(0) as ImageView
            var text =query.get(1) as TextView
            image.setBackgroundResource(R.drawable.tab_home_page_ic_select)
            text.setTextColor(Color.parseColor("#6fd292"))
            adLoad(1,contexts,activitys)
        }

        unitChange.setOnClickListener {
            changeFragments(stackFragment.elementAt(1))
            clearStyle()
            var image =unitChange.get(0) as ImageView
            var text =unitChange.get(1) as TextView
            image.setBackgroundResource(R.drawable.tab_two_ic_select)
            text.setTextColor(Color.parseColor("#6fd292"))
            adLoad(2,contexts,activitys)
        }

        mine.setOnClickListener {
            changeFragments(stackFragment.elementAt(2))
            clearStyle()
            var image =mine.get(0) as ImageView
            var text =mine.get(1) as TextView
            image.setBackgroundResource(R.drawable.tab_mine_ic_select)
            text.setTextColor(Color.parseColor("#6fd292"))
            adLoad(3,contexts,activitys)

        }

    }

    /**
     * fragment 切换
     */

    fun changeFragments(fragment: Fragment){

        val beginTransaction = supportFragmentManager.beginTransaction()
        beginTransaction.replace(R.id.fragment , fragment)
        beginTransaction.commit()


    }

    private fun showAlertDialog() {
        val alertDialog2: AlertDialog = AlertDialog.Builder(this@MainActivity)
            .setMessage("设备异常！！")
            .setPositiveButton(
                "确定",
                DialogInterface.OnClickListener { dialogInterface, i ->
                    android.os.Process.killProcess(android.os.Process.myPid());
                })
            .create()
        //防止返回键把对话框取消掉
        alertDialog2.setCancelable(false)
        alertDialog2.setOnKeyListener(DialogInterface.OnKeyListener { dialog, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                true
            } else {
                false //默认返回false
            }
        })
        alertDialog2.show()
    }


    /**
     * 清除样式
     */
    fun clearStyle(){

        val btWrapper = findViewById<LinearLayout>(R.id.btn_wrapper)
        for (i in 0 until btWrapper.childCount) {
            val itemChild = btWrapper.get(i) as LinearLayout;
            val imageView = itemChild.get(0) as ImageView
            val textView = itemChild.get(1) as TextView
            imageView.setBackgroundResource(0)
            val barItemBean = bottomBarItemBeans.get(i)
            imageView.setBackgroundResource(barItemBean.iconUnselect)
            textView.setTextColor(barItemBean.unselectColor)
        }
    }





    override fun onResume() {
        super.onResume()

    }


    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }




    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        // 监听返回键，点击两次退出程序
        if (  SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD)  && keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
//            if (true) {
            showExitDialog()
//            } else {
//                moveTaskToBack(true)
//            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }


    var exitPopupView: BasePopupView? = null
    var isExitApp = false
    private fun showExitDialog() {

        val customPopup =
            RTExitDialogPopup(this)
        customPopup.listener = object : RTExitDialogPopup.OnExitClickListener {
            override fun cancel() {
                isExitApp = true
            }

            override fun closeDialog() {
                isExitApp = false
            }

            override fun ok() {
                isExitApp = false


            }


        }
        exitPopupView = XPopup.Builder(this)
            .autoOpenSoftInput(false)
            .autoDismiss(false)
//            .enableDrag(false)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asCustom(customPopup)
            .show()

    }
    fun adLoad( position:Int ,context: Context ,activity: Activity){
        val ad2 = SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD_2) //自然流量广告模式

        LogUtil.i(Const.TAG,"MainActivity---------------adLoad----------------"+position)
        if (SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD) || (position == 0 && ad2) ) {


            val adservice = AsService()
            var mFeedContainer: FrameLayout? = null
            var mFeedContainer2: FrameLayout? = null

            var feedId = resources.getString(R.string.feed_native_media_id)
            var feedId2 = resources.getString(R.string.feed_native_media_2_id)
            if (0 == position) {
                mFeedContainer = stackFragment.elementAt(0).activity?.findViewById(R.id.fl_content_1);
//                    mFeedContainer2 = mainFragment.activity?.findViewById(R.id.fl_content_11);
            }  else if (1 == position) {
                mFeedContainer = stackFragment.elementAt(1).activity?.findViewById(R.id.fl_content_2);
//                mFeedContainer2 = waterFragment.activity?.findViewById(R.id.fl_content_11);
            }else  if  (2 == position) {
                    mFeedContainer = stackFragment.elementAt(2).activity?.findViewById(R.id.fl_content_3);
//                  mFeedContainer2 = fortuneFragment.fl_content_22;
             }
            adservice.initAd(
                "feed",
                context,
                feedId,
                mFeedContainer
            )

            adservice.showAd("feed", activity)


//            if(mFeedContainer2!=null) {
//
//                adservice.initAd(
//                    "feed2",
//                    context,
//                    feedId2,
//                    mFeedContainer
//                )
//
//                adservice.showAd("feed2", activity)
//            }

//
//            if (!MyStringUtil.dayIfAdOne(position.toString())) {
//                MyStringUtil.setDayIfAdOne(position.toString())



            //插屏

            adservice.initAd("full", context, resources.getString(R.string.full_media_id), null)


            ////            //插屏


            //显示插屏
            Handler().postDelayed({ adservice.showAd("full", activity) }, 1500)

            if (!ad2) {
//                if (position == -1) {

                //首次 双插屏
//                val isFirstLaunchApp: Boolean =
//                    SharedPreferencesUtil.getStatus("first_launch_list_fragment")
//                if (!isFirstLaunchApp && Const.shuangInterstitialFull || position!=0) {
                adservice.initAd(
                    "full2", context, resources.getString(R.string.full_media_2_id),
                    null
                )


                Handler().postDelayed({adservice.showAd("full2", activity) }, 1500)

                SharedPreferencesUtil.saveStatus("first_launch_list_fragment", true);
//                }

            }
//            }

        }

    }
    override fun scanMusic(isAutoScan: Boolean) {
        TODO("Not yet implemented")
    }
}